package com.hhd.pdf.components;


import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.utils.PdfUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfDiv;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.List;


@Component
public class SectionComponent3 extends AbstractInlineComponent {

    @Override
    public void parseComponent(Element element, GeneratorContext context) throws Exception {
        PdfDiv pdfDiv = getPdfDiv(element, context, null);
        context.getDocument().add(pdfDiv);
    }

    private PdfDiv getPdfDiv(Element element, GeneratorContext context, String parsedFormula) throws DocumentException, IOException {
//        Font font = PdfUtils.createFont(10, PdfUtils.createColor(48, 111, 220));
        Font font = context.getGeneratorParameters().getFont();
        List<com.itextpdf.text.Element> elements = parseSimpleNode(element, context);
        Image image = PdfUtils.getImage("SectionBar1.png");

        PdfPTable table = PdfUtils.createTable(new float[]{1, 50});
        PdfPCell cell = PdfUtils.createCell(image);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        PdfPCell pdfPCell = PdfUtils.getPdfPCell();

        if (CommonUtils.isEmpty(parsedFormula)) {
            for (com.itextpdf.text.Element element1 : elements) {
                if (element1 instanceof Phrase) {
                    Phrase phrase = (Phrase) element1;
                    phrase.setFont(font);
                }
                pdfPCell.addElement(element1);
            }
        } else  {
            pdfPCell.addElement(PdfUtils.createParagraph(parsedFormula, font, Paragraph.ALIGN_LEFT));
        }
        pdfPCell.setMinimumHeight(27);
        pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
        table.addCell(pdfPCell);

        PdfDiv pdfDiv = PdfUtils.wrapDiv(table, 0, 0, 0, 35);
        return pdfDiv;
    }

    @Override
    public String getName() {
        return "section3";
    }

    @Override
    public String getFormula(DefaultElement defaultElement) {
        return defaultElement.getText();
    }

    @Override
    public Collection<? extends com.itextpdf.text.Element> createPdfElement(DefaultElement defaultElement, GeneratorContext context, String parsedFormula) throws DocumentException, IOException {
        return CommonUtils.newList(getPdfDiv(defaultElement, context, parsedFormula));
    }
}
